package com.bort.system.utils;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class FileUtils {

    @Value("${uploadRootPath:D:/workspace/bort/images/}")
    private String root;

    public Result<String> upload(MultipartFile file, String filePath){
        Result<String> result = new Result<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
        String path = "upload/"+dateFormat.format(new Date())+"/"+filePath;
        File dir =  new File(root+path);
        if(!dir.isDirectory()){
            dir.mkdirs();
        }
        String orgName = file.getOriginalFilename();
        String suffix = orgName.substring(orgName.lastIndexOf("."));
        String fileName = RandomStringUtils.randomAlphabetic(4)+System.currentTimeMillis()/1000 + suffix;
        try {
            File target = new File(root+path+"/"+fileName);
            file.transferTo(target);
            result.setData(path+"/"+fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result.setCode(0);
            result.setMsg(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            result.setCode(0);
            result.setMsg(e.getMessage());
        }
        return result;
    }

}
